package com.ics.tongdb.jcq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.sobte.cqp.jcq.event.JcqApp;
import java.awt.Component;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * @author lisiqun
 * @version V1.0
 * @Description:
 * @Company:G'YUN NETWORK TECHNOLOGY
 * @date 2020-04-13 11:39
 */
public class SocketHandler extends IoHandlerAdapter {
    public SocketHandler() {
    }

    public void sessionOpened(IoSession session) {
        System.out.println("创建session连接");
    }

    public void sessionClosed(IoSession session) {
        System.out.println("会话连接关闭");
        session.closeNow();
    }

    public static void downloadUsingNIO(String urlStr, String file) throws IOException {
        URL url = new URL(urlStr);
        ReadableByteChannel rbc = Channels.newChannel(url.openStream());
        FileOutputStream fos = new FileOutputStream(file);
        fos.getChannel().transferFrom(rbc, 0L, 9223372036854775807L);
        fos.close();
        rbc.close();
    }

    public void paseInfo(String model, String reply, long fromqq) {
        String[] msgTemp = model.split("】:");
        String content = msgTemp[msgTemp.length - 1];
        Document doc = null;

        try {
            doc = Jsoup.parse(content);
        } catch (Exception var19) {
            JcqApp.CQ.logInfo("[JCQ] TEST Demo", "e:" + var19);
        }

        Elements els = doc.body().select("p");
        String msg1 = "";
        List<String> imgs = new ArrayList();
        Iterator var11 = els.iterator();

        String directory;
        String[] imgNameList;
        while(var11.hasNext()) {
            Element el = (Element)var11.next();
            directory = el.select("img").attr("src");
            if (!directory.isEmpty()) {
                imgs.add(directory);
                imgNameList = directory.split("/");
                directory = imgNameList[imgNameList.length - 1];
                msg1 = msg1 + "[CQ:image,file=" + directory + "]" + el.text() + "\n";
            } else {
                msg1 = msg1 + el.text() + "\n";
            }
        }

        if (!imgs.isEmpty()) {
            var11 = imgs.iterator();

            while(var11.hasNext()) {
                String img = (String)var11.next();
                directory = System.getProperty("user.dir") + "/data/image";
                imgNameList = img.split("/");
                String imgName = imgNameList[imgNameList.length - 1];
                String fileDir = directory + "/" + imgName;

                try {
                    downloadUsingNIO(img, fileDir);
                } catch (IOException var18) {
                    var18.printStackTrace();
                }
            }
        }

        Application.CQ.sendPrivateMsg(fromqq, reply + msg1);
    }

    public String paseInfo(SocketMessage model, String reply) {
        if (!model.getMsg().contains("<p>")) {
            JcqApp.CQ.logInfo("[JCQ] TEST Demo", model.getMsg());
            return reply + model.getMsg();
        } else {
            String[] msgTemp = model.getMsg().split("】:");
            String content = msgTemp[msgTemp.length - 1];
            JcqApp.CQ.logInfo("[JCQ] TEST Demo", "content:" + content);
            Document doc = null;

            try {
                doc = Jsoup.parse(content);
            } catch (Exception var17) {
                JcqApp.CQ.logInfo("[JCQ] TEST Demo", "e:" + var17);
                JOptionPane.showMessageDialog((Component)null, "富文本消息处理错误：" + var17, "错误", 0);
            }

            JcqApp.CQ.logInfo("[JCQ] TEST Demo", "doc:" + doc.text());
            Elements els = doc.body().select("p");
            String msg1 = "";
            if (msgTemp.length > 1 && msgTemp[0].contains("【")) {
                msg1 = msgTemp[0] + "】:";
            }

            List<String> imgs = new ArrayList();
            Iterator var9 = els.iterator();

            String directory;
            String[] imgNameList;
            while(var9.hasNext()) {
                Element el = (Element)var9.next();
                directory = el.select("img").attr("src");
                if (!directory.isEmpty()) {
                    imgs.add(directory);
                    imgNameList = directory.split("/");
                    directory = imgNameList[imgNameList.length - 1];
                    msg1 = msg1 + "[CQ:image,file=" + directory + "]" + el.text() + "\n";
                } else {
                    msg1 = msg1 + el.text() + "\n";
                }
            }

            JcqApp.CQ.logInfo("[JCQ] TEST Demo", "msg1:" + msg1);
            if (!imgs.isEmpty()) {
                var9 = imgs.iterator();

                while(var9.hasNext()) {
                    String img = (String)var9.next();
                    img = img.replace("\\", "").replace("\"", "");
                    JcqApp.CQ.logInfo("[JCQ] TEST Demo", "img:" + img);
                    directory = System.getProperty("user.dir") + "/data/image";
                    imgNameList = img.split("/");
                    String imgName = imgNameList[imgNameList.length - 1];
                    JcqApp.CQ.logInfo("[JCQ] TEST Demo", "imgName:" + imgName);
                    String fileDir = directory + "/" + imgName;

                    try {
                        JcqApp.CQ.logInfo("[JCQ] TEST Demo", "准备开始下载图片" + img + "   " + fileDir);
                        downloadUsingNIO(img, fileDir);
                    } catch (IOException var16) {
                        var16.printStackTrace();
                        JcqApp.CQ.logInfo("[JCQ] TEST Demo", var16.getMessage());
                        JOptionPane.showMessageDialog((Component)null, "图片下载错误：" + var16.getMessage(), "错误", 0);
                    }
                }
            }

            return reply + msg1;
        }
    }

    public void messageReceived(IoSession session, Object obj) throws Exception {
        String msg = obj.toString();
        if ("RQ".equals(msg)) {
            session.write("RS");
        } else {
            SocketMessage model = (SocketMessage) JSON.parseObject(msg, SocketMessage.class);
            System.out.println(JSONObject.toJSONString(model));
            String action = model.getAction();
            if (StringUtils.isEmpty(action)) {
                System.out.println("SocketHandler.messageReceived recive action is null!");
            }

            String reply = "";
            SocketAction socketAction = SocketAction.valueOf(action);
            switch(socketAction) {
                case BIND:
                    if (!"1.0.4".equals(model.getVersion())) {
                        StringUtils.getJOptionPane(model.getMsg());
                        SocketClient.server.closeOnFlush();
                    }
                    break;
                case CLOSE_WINDOWS:
                    System.out.println("socketAction");
                    System.out.println("执行关机命令");
                    Runtime rt = Runtime.getRuntime();
                    rt.exec("cmd.exe /c shutdown -f -s -t 0");
                    break;
                case MESSAGE:
                    try {
                        if (model.getQq() != null && !"".equals(model.getQq())) {
                            reply = JcqApp.CC.at(new long[]{Long.parseLong(model.getQq())});
                        }

                        if (model.getGroup() != null) {
                            Application.CQ.sendGroupMsg(Long.parseLong(model.getGroup()), this.paseInfo(model, reply));
                        } else if (model.getDiscuss() != null) {
                            Application.CQ.sendDiscussMsg(Long.parseLong(model.getDiscuss()), this.paseInfo(model, reply));
                        } else {
                            Application.CQ.sendPrivateMsg(Long.parseLong(model.getQq()), this.paseInfo(model, ""));
                        }
                    } catch (Exception var10) {
                        var10.printStackTrace();
                    }

                    model.setAction(SocketAction.RECEIVE_REPLY.toString());
                    session.write(JSON.toJSONString(model, new SerializerFeature[]{SerializerFeature.WriteDateUseDateFormat}));
            }

        }
    }

    public void messageSent(IoSession session, Object obj) {
        String msg = obj.toString();
        if (!"RS".equals(msg)) {
            System.out.println("客户端消息已发送成功，发送数据:" + msg);
        }

    }
}
